/*
 * Copyright (C) 2025 ameise <ameise.wang@gmail.com> - All Rights Reserved
 *
 * This file is part of e3lock.
 *
 * e3lock is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * e3lock is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with e3lock. If not, see <https://www.gnu.org/licenses/>.
 */

package e3lock

import (
	"context"
	"github.com/redis/go-redis/v9"
	"sync"
	"sync/atomic"
	"time"
)

var (
	scriptOnce      Once
	scriptUnlockSHA string
	scriptWatchSHA  string
)

func NewRedisLock(cli redis.UniversalClient, key string, token string, ttl ...time.Duration) Locker {
	scriptOnce.Do(func() {
		scriptUnlockSHA = cli.ScriptLoad(context.Background(), scriptUnlock).Val()
		scriptWatchSHA = cli.ScriptLoad(context.Background(), scriptWatch).Val()
	})

	t := 20 * time.Second
	if ttl != nil && len(ttl) > 0 && ttl[0] > 0 {
		t = ttl[0]
	}
	return &redisLock{
		cli:   cli,
		key:   "_redis_lock:" + key,
		token: token,
		ttl:   t,
	}
}

type redisLock struct {
	mu     SpinLock
	cli    redis.UniversalClient
	key    string
	token  string
	ttl    time.Duration
	isLock atomic.Bool
	tr     *time.Timer
	wg     sync.WaitGroup
}

func (ts *redisLock) doRedisLock() bool {
	r := ts.cli.SetNX(context.Background(), ts.key, ts.token, ts.ttl)
	ok := r.Val()
	if ok {
		ts.isLock.Store(true)
		ts.wg.Add(1)
		ts.tr = time.NewTimer(ts.ttl / 2)
		go ts.startWatchDog()
	}
	return ok
}

func (ts *redisLock) startWatchDog() {
	k := ts.ttl / 2
loopFor:
	for {
		select {
		case <-ts.tr.C:
			if !ts.isLock.Load() {
				break loopFor
			}
			r := ts.cli.EvalSha(context.Background(), scriptWatchSHA, []string{ts.key}, ts.token, ts.ttl.Milliseconds())
			if v, err := r.Int64(); err != nil || v == 0 {
				break loopFor
			}
			ts.tr.Reset(k)
		}
	}

	if ts.isLock.CompareAndSwap(true, false) {
		if _gLogger != nil {
			_gLogger.WarnPrintf("redis key[%s] expired failed", ts.key)
		}
		ts.tr.Stop()
		select {
		case <-ts.tr.C:
		default:
		}
		ts.tr = nil
		ts.mu.Unlock()
	}
	ts.wg.Done()
}
